/**
 * C Implementation: grib_get_data
 *
 * Description:
 * how to get lat/lon/values from a GRIB message
 * 如何读取 lat/lon/values
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include "eccodes.h"

int sfx_grib_get_data()
{
    int err  = 0;
    size_t i = 0;

    // D:/sfxData/ECMWF/eccodes_test_data/reduced_latlon_surface.grib1
    const char* filename = "D:/sfxData/ECMWF/eccodes_test_data/reduced_latlon_surface.grib1";

    FILE* in = fopen(filename, "rb");

    // create new handle from a message in a file
    codes_handle* h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);

    // set missing value
    // 设置缺失值
    const double missing = 9999.0;
    CODES_CHECK(codes_set_double(h, "missingValue", missing), 0);

    // 获取格点数量 (313362)
    long numberOfPoints = 0;
    CODES_CHECK(codes_get_long(h, "numberOfPoints", &numberOfPoints), 0);

    // 分配数据空间
    double* lons   = (double*)malloc(numberOfPoints * sizeof(double));
    double* lats   = (double*)malloc(numberOfPoints * sizeof(double));
    double* values = (double*)malloc(numberOfPoints * sizeof(double));

    CODES_CHECK(codes_grib_get_data(h, lats, lons, values), 0);

    // 
    // 格点数据
    // dlon = 1.406 dlat = 0.36
    // 
    double lat_prv   = 1e-12;
    for (i = 0; i < numberOfPoints - 1; i++) {
        if (values[i] != missing) {
            double lat_cur = lats[i];
            if (fabs(lat_cur - lat_prv) > 1e-12) {
                lat_prv = lat_cur;
                printf("-----------------------------------------------------------\n");
            }
            else {
                printf("%8.3f %8.3f %8.3f\n", lats[i], lons[i], values[i]);
            }
        }
    }

    free(values);
    free(lats);
    free(lons);
    codes_handle_delete(h);
    fclose(in);

    return 0;
}

